package com.wd.cloud.applet.common;

import com.alibaba.fastjson.JSONObject;
import com.wd.cloud.applet.common.constant.dataverify.Constant;
import com.wd.cloud.applet.common.exception.CustomException;
import com.wd.cloud.applet.entity.bo.ShopUserInfo.ShopUserInfoLoginReq;
import com.wd.cloud.applet.entity.vo.ShopUserInfo.ShopUserInfoLoginResp;
import com.wd.cloud.applet.utils.HelperUtils;
import com.wd.cloud.applet.utils.cache.RedisUtil;
import java.util.Base64;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 网点用户登录信息安全工具类
 *
 * @author moyiyang
 */
@Component
public class RetailersSecurityUtils {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RedisUtil redisUtil;
    /**
     * 获取请求头的accessToken
     * @return
     */
    public String getAccessToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String accessToken = request.getHeader("accessToken");
        logger.info("获取用户accessToken信息"+accessToken);
        if (accessToken == null || accessToken.isEmpty()) {
            throw new CustomException("accessToken不能为空", 1003);
        }
        return accessToken;
    }
    /**
     * 获取用户id
     *
     * @return
     */
    public String getUserId(ShopUserInfoLoginReq params) {
        String accessToken= redisUtil.getString(Constant.SHOP_USER_TOKEN_PREFIX_KEY + params.getPhone());
        return accessToken;
    }
    /**
     * 获取登录的用户信息
     */
    public ShopUserInfoLoginResp getLoginUserInfo() {
        String realToken = new String(Base64.getDecoder().decode(getAccessToken()));
        ShopUserInfoLoginResp userInfo = JSONObject.parseObject(realToken, ShopUserInfoLoginResp.class);
        if (HelperUtils.checkObjAllFieldsIsNull(userInfo)) {
            throw new CustomException("非法accessToken", 1006);
        }
        String redisUser = redisUtil.getString(Constant.SHOP_USER_TOKEN_PREFIX_KEY + userInfo.getPhone());
        if (redisUser == null || redisUser.isEmpty()) {
            throw new CustomException("未登录或登录已过期", 1005);
        }
        String objShopInfo = new String(Base64.getDecoder().decode(redisUser));
        return JSONObject.parseObject(objShopInfo, ShopUserInfoLoginResp.class);
    }
}
